import turbogears as tg
from turbogears import controllers, expose, flash, validators, validate, redirect
from turbogears.widgets import WidgetsList, TableForm, HiddenField, CalendarDatePicker, TextField
from bookloantracker.model import *
import logging
log = logging.getLogger("bookloantracker.loaner")

from cherrypy import session

class LoanerFormList(WidgetsList):
    name = TextField(label=_("Name"),
                     validator=validators.NotEmpty(),
                     attrs={"size":"70"})
    birthDate = CalendarDatePicker(label=_("Birth date"),
                                   format="%d/%m/%Y",
                                   calendar_lang="pt_BR",
                                   button_text=(_("Choose")))
    phoneNumber = TextField(label=_("Phone"),
                            attrs={"size":"70"})
    email = TextField(label=_("E-mail"),
                      attrs={"size":"70"})
    address = TextField(label=_("Address"),
                      attrs={"size":"70"})
    retInfo = HiddenField()


loanerForm = TableForm(
    fields = LoanerFormList(),
    action = "save",
    submit_text = _("Submit")
    )


class LoanerCadaster(controllers.Controller):
    @expose()
    def default(self, *k, **kw):
        redirect(tg.url("/"))

    @expose(template="bookloantracker.templates.authorcadaster")
    def index(self, name=None, ret=None):
        values = {}
        if name:
            values["name"] = name
        if ret:
            values["retInfo"] = ret
        return dict(form = loanerForm,
                    values = values)

    @expose()
    @validate(validators={"birthDate": validators.DateConverter(month_style="dd/mm/yyyy")})
    def save(self, name, birthDate=None,
             phoneNumber=None, email=None,
             address=None, retInfo=None):
        redirectTarget = "index"
        if retInfo:
            redirectTarget = "/"+"/".join(retInfo.split("."))
        log.debug("redirectTarget = %s" % redirectTarget)
        loanerList = Loaner.select(LIKE(Loaner.q.name,name))
        if loanerList.count():
            flash(_("Loaner alredy registered"))
            redirect(redirectTarget)
        loaner = Loaner(name = name,
                        birthDate = birthDate,
                        phoneNumber = phoneNumber,
                        email = email,
                        address = address)
        flash(_("Loaner registered"))
        redirect(redirectTarget)
        return {}
